<?php

/**
 * The main page and login form.
 * @author Jamie Dockendorff <j.dockendorff@gmail.com>
 * @version 1.0
 * @since 2013-11-16
 */

require_once 'database.php';

function check_login ($username, $password) {

	if (!isset ($username)) {
		echo "A username is required.<br>\n";
		return;
	}

	if (!isset ($password)) {
		echo "A password is required.<br>\n";
		return;
	}

	$db = new database ($username, $password);
	if ($db->connect_errno ()) {
		// It failed, return to login page.
		echo "Invalid username/password combination.";
		return;
	}

	$db->close ();

	loginInfo::set_login ($username, $password);

	// And go to the daily schedule page.
	$date = getdate();
	$day = sprintf ("%d_%d_%d", (int)$date['year'], (int)$date['mon'], (int)$date['mday']);

	header("location:/view_day.php?day=" . $day);
}

if ($_GET && !strcmp ($_GET['action'], "logout")) {
	// Process logout.
	loginInfo::logout ();
} else if ($_POST) {
	check_login ($_POST['username'], $_POST['password']);
} else if (isset ($_COOKIE[loginInfo::user_cookie])) {
	check_login ($_COOKIE[loginInfo::user_cookie], $_COOKIE[loginInfo::passwd_cookie]);
}

?>

<html>
	<head>
		<title> Opol - The Optimizer of PrOduction Lines </title>
	</head>
	<body>
		<link rel="stylesheet" type="text/css" href="opol.css">
		<form id='login' action='/' method='post' accept-charset='UTF-8'>
			<fieldset>
				<legend>Login</legend>
				<input type='hidden' name='submitted' id='submitted' value='1'/>
 
				<label for='username' >Username*:</label><br>
				<input type='text' name='username' id='username'  maxlength="50" /><br>
 
				<label for='password' >Password*:</label><br>
				<input type='password' name='password' id='password' maxlength="50" /><br>

				<input type='submit' name='Submit' value='Submit' /><br>
			</fieldset>
		</form>
	</body>
</html>
